package cmsi.utils.weixinpay;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by LV on 2016/4/7 0007.
 * Email:LvLoveYuForever@gmail.com
 */
public class XMLParser {

    private static Logger log=Logger.getLogger(XMLParser.class);
    /**
     * 将返回的xml的数据转换成map
     * @param xmlString
     * @return
     * @throws ParserConfigurationException
     * @throws IOException
     * @throws SAXException
     */
    public static Map<String,Object> getMapFromXML(String xmlString) throws ParserConfigurationException, IOException, SAXException {

        //这里用Dom的方式解析回包的最主要目的是防止API新增回包字段
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        InputStream is =  Util.getStringStream(xmlString);
        Document document = builder.parse(is);

        //获取到document里面的全部结点
        NodeList allNodes = document.getFirstChild().getChildNodes();
        Node node;
        Map<String, Object> map = new HashMap<String, Object>();
        int i=0;
        while (i < allNodes.getLength()) {
            node = allNodes.item(i);
            if(node instanceof Element){
                map.put(node.getNodeName(),node.getTextContent());
            }
            i++;
        }
        return map;

    }

    /**
     * 商户处理后同步返回给微信参数,转换成xml类型
     * @param return_code
     * @param return_msg
     * @return
     */
    public static String setXML(String return_code,String return_msg) {
        return "<xml><return_code><![CDATA[" + return_code +
                "]]></return_code><return_msg><![CDATA[" +
                return_msg + "]]></return_msg></xml>";


    }

    public static String mapToXML(Map<String,Object> map){
        //将map类型的请求参数装换成XML格式
        StringBuilder sb=new StringBuilder();
        sb.append("<xml>");
        Iterator it=map.entrySet().iterator();
        while (it.hasNext()){
            Map.Entry entry= (Map.Entry) it.next();
            String k= (String) entry.getKey();
            String v= (String) entry.getValue();
            sb.append("<"+k+">"+v+"</"+k+">");
        }
        sb.append("</xml>");
        log.info("转换xml格式："+sb.toString());
        return sb.toString();
    }

}
